// Toast.tsx
import React, { useEffect, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Animated,
  Easing,
  Dimensions,
  TouchableWithoutFeedback,
} from 'react-native';
import { ToastOptions, ToastType, ToastPosition } from './types'; // 确保路径正确

interface ToastProps extends ToastOptions {
  onClose: () => void;
}

const Toast: React.FC<ToastProps> = ({
  message,
  type = 'info',
  duration = 5000, // 增加默认显示时长到5秒
  position = 'bottom',
  onClose,
  icon = null,
  style,
  textStyle,
  showMask = false,
}) => {
  const opacityAnim = useRef(new Animated.Value(0)).current;
  const spinAnim = useRef(new Animated.Value(0)).current;

  // 旋转动画（用于loading）
  const spin = spinAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  useEffect(() => {
    // 显示动画
    Animated.timing(opacityAnim, {
      toValue: 1,
      duration: 200,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start();

    // 如果不是loading类型且设置了duration，则定时关闭
    let timer: number;
    if (type !== 'loading' && duration > 0) {
      timer = setTimeout(() => {
        hideToast();
      }, duration);
    }

    // 启动旋转动画
    if (type === 'loading') {
      Animated.loop(
        Animated.timing(spinAnim, {
          toValue: 1,
          duration: 200,
          easing: Easing.linear,
          useNativeDriver: true,
        }),
      ).start();
    }

    return () => {
      clearTimeout(timer);
    };
  }, [opacityAnim, duration, type, spinAnim]);

  const hideToast = () => {
    // 隐藏动画
    Animated.timing(opacityAnim, {
      toValue: 0,
      duration: 200,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start(() => {
      onClose();
    });
  };

  const renderIcon = () => {
    if (icon !== null) {
      // 如果传入了自定义图标，直接渲染
      if (icon) {
        return <View style={styles.iconContainer}>{icon}</View>;
      }

      // 否则根据类型渲染默认图标
      let iconColor: string;
      switch (type) {
        case 'success':
          iconColor = '#52c41a';
          break;
        case 'error':
          iconColor = '#ff4d4f';
          break;
        case 'warning':
          iconColor = '#faad14';
          break;
        case 'info':
          iconColor = '#1890ff';
          break;
        case 'loading':
          return (
            <View style={styles.iconContainer}>
              <Animated.View
                style={[styles.loadingIcon, { transform: [{ rotate: spin }] }]}
              />
            </View>
          );
        default:
          iconColor = '#333';
      }
      return (
        <View style={styles.iconContainer}>
          <View style={[styles.iconBase, { backgroundColor: iconColor }]} />
        </View>
      );
    }
    return null;
  };

  return (
    <View
      style={[styles.container, styles[`container_${position}`]]}
      pointerEvents="box-none"
    >
      {showMask && (
        <TouchableWithoutFeedback onPress={hideToast}>
          <View style={styles.mask} />
        </TouchableWithoutFeedback>
      )}
      <Animated.View
        style={[
          styles.toastBox,
          style,
          { opacity: opacityAnim }, // 应用透明度动画
        ]}
      >
        {renderIcon()}
        <Text style={[styles.message, textStyle]}>{message}</Text>
      </Animated.View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 9999,
  },
  container_top: {
    justifyContent: 'flex-start',
    paddingTop: Dimensions.get('window').height * 0.1,
  },
  container_center: {
    justifyContent: 'center',
  },
  container_bottom: {
    justifyContent: 'flex-end',
    paddingBottom: Dimensions.get('window').height * 0.1,
  },
  mask: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'transparent',
  },
  toastBox: {
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 8,
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 20,
    maxWidth: '80%',
  },
  iconContainer: {
    marginRight: 8,
  },
  iconBase: {
    width: 20,
    height: 20,
    borderRadius: 10,
  },
  loadingIcon: {
    width: 20,
    height: 20,
    borderRadius: 10,
    borderWidth: 2,
    borderColor: '#fff',
    borderTopColor: 'transparent',
  },
  message: {
    color: '#fff',
    fontSize: 14,
    flexShrink: 1,
  },
});

export default Toast;
